package com.tanhua.dubbo.api;

import com.mongodb.client.result.DeleteResult;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class CommentApiImpl implements CommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 分页查询
     *
     * @return
     */
    public List<Comment> findComments(String movementId, CommentType commentType, Integer page, Integer pagesize) {
        //1、构造查询条件
        Query query = Query.query(Criteria.where("publishId").
                is(new ObjectId(movementId)).and("commentType")
                .is(commentType.getType()))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //2、查询并返回
        return mongoTemplate.find(query, Comment.class);
    }


    /**
     * 发布评论,或点赞,或喜欢,并获取相应数量
     */
    @Override
    public Integer save(Comment comment) {
        //1、查询动态
        Movement movement = mongoTemplate.findById(comment.getPublishId(), Movement.class);
        //2.向comment对象设置被评论人属性
        if (movement != null) {
            comment.setPublishUserId(movement.getUserId());
        }
        //3.保存到数据库
        mongoTemplate.save(comment);

        //4更新动态表中对应的字段
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", 1);
        } else if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", 1);
        } else {
            update.inc("loveCount", 1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        Movement modify = mongoTemplate.findAndModify(query, update, options, Movement.class);
        //5、获取最新的评论数量，并返回
        return modify.statisCount(comment.getCommentType());
    }

    /**
     * 判断comment点赞,喜欢数据是否存在
     */
    @Override
    public Boolean hasComment(String movementId, Long userId, CommentType commentType) {
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(movementId))
                .and("commentType").is(commentType.getType());
        Query query = Query.query(criteria);
        boolean exists = mongoTemplate.exists(query, Comment.class);
        return exists;
    }


    /**
     * 删除点赞或喜欢
     *
     * @param comment
     * @return
     */
    @Override
    public Integer delete(Comment comment) {
        //1.根据userId,类型,动态Id,删除(评论表的数据)
        Criteria criteria = Criteria.where("userId").is(comment.getUserId())
                .and("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query, Comment.class);
        //2.更新动态表数据
        Query movementQuery =
                Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        //如果是点赞,评论,喜欢  -1
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", -1);
            //评论  -1
        } else if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", -1);
            //喜欢  -1
        } else {
            update.inc("loveCount", -1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        Movement modify = mongoTemplate.
                findAndModify(movementQuery, update, options, Movement.class);
        //返回记录数
        return modify.statisCount(comment.getCommentType());
    }

    /**
     * 查询是否点赞该评论
     *
     * @param commentId 评论的id
     * @param userId    操作用户id
     * @param like      点赞
     * @return
     */
    @Override
    public Boolean hasLikeComment(String commentId, Long userId, CommentType like) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(commentId))
                .and("commentType").is(like.getType()));
        //判断数据是否存在,并返回
        return mongoTemplate.exists(query, Comment.class);
    }


    /**
     * 保存对评论的点赞,评论操作
     *
     * @param comment
     * @return
     */
    @Override
    public Integer saveComment(Comment comment) {
        //1.通过被评论的评论id查询被评论的人id
        Comment comm = mongoTemplate.findById(comment.getPublishId(), Comment.class);
        //2.判断该评论是否存在
        if (comm != null) {
            //存在,设置被评论(点赞)人的id --comm评论人的id就是现在被电点赞的id
            comment.setPublishUserId(comm.getUserId());
        }
        //2.添加数据保存点赞到MongoDB
        mongoTemplate.save(comment);
        //更新评论表字段
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        //update.inc加1
        update.inc("likeCount", 1);
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        Comment modify = mongoTemplate.findAndModify(query, update, options, Comment.class);
        //5、获取最新的评论数量，并返回
        return modify.statesCount(comment.getCommentType());
    }

    /**
     * 删除对评论的点赞,评论
     *
     * @param comment
     * @return
     */
    @Override
    public Integer deleteComment(Comment comment) {
        //1、删除Comment表数据
        Criteria criteria = Criteria.where("userId").is(comment.getUserId())
                .and("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query, Comment.class);

        //2、修改评论表中的总数量
        Query commentQuery = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();

        update.inc("likeCount", -1);

        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        Comment modify = mongoTemplate.findAndModify(commentQuery, update, options, Comment.class);
        //5、获取最新的评论数量，并返回
        return modify.statesCount(comment.getCommentType());
    }
}